package freespiritsocial.io.user.ui.fragment.home

import android.os.Bundle
import androidx.core.os.bundleOf
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.scwang.smart.refresh.layout.util.SmartUtil.dp2px
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.databinding.FrgHomeFollowingBinding
import freespiritsocial.io.user.decoration.SpaceItemDecoration
import freespiritsocial.io.user.ext.init
import freespiritsocial.io.user.ext.loadListData
import freespiritsocial.io.user.ui.adapter.FollowedAdapter
import freespiritsocial.io.user.ui.adapter.FollowedPostAdapter
import freespiritsocial.io.user.ui.fragment.mine.MineFrg.Companion.KEY_IS_USER
import freespiritsocial.io.user.ui.fragment.mine.MineFrg.Companion.KEY_USER
import freespiritsocial.io.user.ui.fragment.post.PostDetailFrg
import freespiritsocial.io.user.ui.helper.PostMoreDialogHelper
import freespiritsocial.io.user.viewmodel.FollowingViewModel
import freespiritsocial.io.user.viewmodel.GetMyFollowsViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction

/**
 * @description 首页关注
 */
class FollowingFrg: BaseFragment<FollowingViewModel,FrgHomeFollowingBinding>() {
    private val getMyFollowsViewModel by activityViewModels<GetMyFollowsViewModel>()
    private val followedAdapter by lazy(LazyThreadSafetyMode.NONE) {
        FollowedAdapter().apply {
            setOnItemClickListener { _,view,position ->
                goToPeopleHome(data[position].userId)
            }
        }
    }
    private val followedPostAdapter by lazy(LazyThreadSafetyMode.NONE) {
        FollowedPostAdapter().apply {
            addChildClickViewIds(R.id.iv_avatar,R.id.iv_cover,R.id.iv_more)
            setOnItemChildClickListener { _,view,position ->
                when (view.id) {
                    R.id.iv_avatar -> goToPeopleHome(data[position].userId)
                    R.id.iv_cover -> mViewModel.getPost(data[position].invitationId)
                    R.id.iv_more -> {
                        PostMoreDialogHelper(this@FollowingFrg,data[position],mViewModel).create()
                    }
                }
            }
        }
    }

    private fun goToPeopleHome(id: String?) {
        mViewModel.getUserInfo(id) {
            nav().navigateAction(R.id.action_mainFrg_to_mineFrg,bundleOf(KEY_IS_USER to false,KEY_USER to it))
        }
    }

    override fun layoutId(): Int = R.layout.frg_home_following

    override fun initView(savedInstanceState: Bundle?) = with(mDatabind) {
        click = Click()
        listFollows.init(
            followedAdapter,
            LinearLayoutManager(requireContext(),RecyclerView.HORIZONTAL,false),
            hasEmpty = false
        )
        listPost.init(
            followedPostAdapter,
            emptyText = "No one has posted any posts yet.",
            emptyImage = R.mipmap.empty_home
        ).addItemDecoration(SpaceItemDecoration(0,dp2px(25f)))
        getMyFollowsViewModel.getFollowList()
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.postItemResult.observe(this) {
            nav().navigateAction(
                R.id.postDetailFrg,
                bundle = bundleOf(PostDetailFrg.KEY_DATA to it)
            )
        }
        mViewModel.postResult.observe(this) {
            loadListData(it,followedPostAdapter,mDatabind.refresh)
        }
        //获取关注列表
        lifecycleScope.launch {
            getMyFollowsViewModel.resultFollow.collect {
                followedAdapter.dealData(it)
            }
        }
        eventViewModel.attentionEvent.observe(this) { id ->
            //如果存在就删除 如果不存在添加
            followedAdapter.data.find { it.userId == id }?.also { getMyFollowsViewModel.removePeople(it) } ?: getMyFollowsViewModel.getPeopleInfo(id)
            mViewModel.getFollowingPostList(true)
        }
        eventViewModel.savePostEvent.observe(this) {
            val postPojo = followedPostAdapter.data.find { data -> data.invitationId == it } ?: return@observe
            postPojo.isSave = postPojo.isSave?.not()
            followedPostAdapter.notifyItemChanged(followedPostAdapter.getItemPosition(postPojo))
        }
        eventViewModel.hidePostEvent.observe(this) {
            val postPojo = followedPostAdapter.data.find { data -> data.invitationId == it } ?: return@observe
            followedPostAdapter.remove(postPojo)
        }
        eventViewModel.likePostEvent.observe(this) {
            val postPojo = followedPostAdapter.data.find { data -> data.invitationId == it } ?: return@observe
            postPojo.isLike = postPojo.isLike?.not()
            postPojo.likeCount += if (postPojo.isLike == true) 1 else -1
            followedPostAdapter.notifyItemChanged(followedPostAdapter.getItemPosition(postPojo))
        }
    }

    override fun dismissLoading() {
        super.dismissLoading()
        mDatabind.refresh.finishRefresh()
        mDatabind.refresh.finishLoadMore()
    }

    override fun lazyLoadData() {
        refresh()
    }

    fun refresh() {
        mViewModel.getFollowingPostList(true)
    }

    inner class Click {
        fun onRefresh() {
            refresh()
        }

        fun onLoadMore() {
            mViewModel.getFollowingPostList()
        }
    }
}